package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.entity.Volunteer;
import com.example.exception.CustomException;
import com.example.mapper.VolunteerMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @志愿者信息业务层
 */
@Service
public class VolunteerService {
    @Resource
    private VolunteerMapper volunteerMapper;

    public void add(Volunteer volunteer) {
        //进行逻辑处理

            Volunteer dbVolunteer = volunteerMapper.selectByUsername(volunteer.getUsername());
            if (ObjectUtil.isNotEmpty(dbVolunteer)) {
                throw new CustomException("用户名已存在");
            }
            if (ObjectUtil.isEmpty(volunteer.getPassword())) {
                volunteer.setPassword("123456");
            }
            volunteer.setRole("VOLUNTEER");
            volunteerMapper.insert(volunteer);
        }

    public PageInfo<Volunteer> selectPage(Volunteer volunteer, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Volunteer> list;
        if(ObjectUtil.isNotEmpty(volunteer.getName())){
            list = volunteerMapper.selectByName(volunteer.getName());
        } else {
            list = volunteerMapper.selectAll();
        }

        return PageInfo.of(list);



    }

    public void updateById(Volunteer volunteer) {
        volunteerMapper.updateById(volunteer);
    }

    public void deleteById(Integer id) {
        volunteerMapper.deleteById(id);
    }

    public Volunteer login(Account account) {
        Volunteer dbVolunteer = volunteerMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbVolunteer)) {
            throw new CustomException("用户不存在");
        }
        if (!account.getPassword().equals(dbVolunteer.getPassword())) {
            throw new CustomException("账号或密码错误");
        }
        return dbVolunteer;
    }

    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        Volunteer dbVolunteer = volunteerMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbVolunteer)) {
            throw new CustomException("用户不存在");
        }
        if (!account.getPassword().equals(dbVolunteer.getPassword())) {
            throw new CustomException("原密码错误");
        }
        dbVolunteer.setPassword(account.getNewPassword());
        volunteerMapper.updateById(dbVolunteer);
    }

    public List<Volunteer> selectAll() {
      return   volunteerMapper.selectAll();
    }

    public Volunteer selectById(Integer id) {
        return volunteerMapper.selectById(id);
    }
}

